package util.lang.sql;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class SqlFilterStatementSet extends SqlFilterStatement {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private List<SqlFilterStatement> listOfFilters;
	private String connector;
	
	public String getConnector() {
		return connector;
	}

	public void setConnector(String connector) {
		this.connector = connector;
	}

	public SqlFilterStatementSet() {
		listOfFilters = new LinkedList<SqlFilterStatement>();
		connector = "AND";
	}
	
	public SqlFilterStatementSet(SqlFilterStatement item) {
		this();
		listOfFilters.add(item);
	}
	public SqlFilterStatementSet(String connector, SqlFilterStatement... items) {
		this();
		for (int i = 0; i < items.length; i++) {
			listOfFilters.add(items[i]);
		}
		this.connector = connector;
	}
	public SqlFilterStatementSet(Iterable<SqlFilterStatement> list) {
		this();
		add(list);
	}
	public SqlFilterStatementSet(String connector, Iterable<SqlFilterStatement> list) {
		this();
		add(list);
		this.connector = connector;
	}
	
	public void add(SqlFilterStatement item) {
		listOfFilters.add(item);
	}
	
	public void add(Iterable<SqlFilterStatement> list) {
        for (Iterator<SqlFilterStatement> i = list.iterator(); i.hasNext();) { 
        	SqlFilterStatement eachItem = (SqlFilterStatement) i.next();
        	listOfFilters.add(eachItem);
        }
	}
	
	@Override
	public String getSql() {
		StringBuffer sb = new StringBuffer();
		String con = " " + connector + " ";
		
        for (Iterator<SqlFilterStatement> i = listOfFilters.iterator(); i.hasNext();) { 
        	SqlFilterStatement eachItem = (SqlFilterStatement) i.next();
        	sb.append('(');
        	sb.append(eachItem.getSql());
        	sb.append(')');
        	sb.append(con);
        }
        
        if (sb.length() == 0)
        	return "TRUE";
        
        return sb.substring(0, sb.length() - con.length());
	}

	@Override
	public LinkedList<Object> getValues() {
		LinkedList<Object> objs = new LinkedList<Object>();
		
        for (Iterator<SqlFilterStatement> i = listOfFilters.iterator(); i.hasNext();) { 
        	SqlFilterStatement eachItem = (SqlFilterStatement) i.next();
        	LinkedList<Object> values = eachItem.getValues();
        	if (values != null) objs.addAll(values);
        }
        
        return objs;
	}
}
